import React from 'react';
import {
  Form,
  Input,
  Button,
  message,
  Modal,
  InputNumber,
  Space,
  Tabs,
  DatePicker,
  Row,
  Col,
  // Select,
  Transfer,
  TreeSelect,
  Radio,
  Spin,
  Table,
  Tag,
} from 'antd';
import { ExclamationCircleOutlined, SearchOutlined } from '@ant-design/icons';
import { connect } from 'umi';
import UploadUtil from '@/components/UploadUtil';
import moment from 'moment';
import  CodeList  from "./CodeList";
import { Color } from 'chalk';

// const { Option } = Select;
const currControl = 'Coupon';
const { confirm } = Modal;
const { TabPane } = Tabs;

class CourseEdit extends React.Component<any, any> {
  constructor(props: any) {
    super(props);
    this.state = {
      loading: false,
      datas: {},
      imageUrl: '',
      imgList: [],
      type: '',
      productData: [],
      params: {},
      cascaderOption: [],
      targetKeys: [],
      selectedKeys: [],
      pageIndex: 1,
      pageSize: 10,
      parentId: '',
      categoryId: null,
      showDiscount: false,
      showDeduction: false,
      showFullminus: false,
      showStudy: false,
      loadingP: false,
    };
  }
  formRef: any = React.createRef();
  componentDidMount() {
    const { ParentData } = this.props;
    if (ParentData && ParentData.id) {
      this.getData(ParentData.id);
      this.setState({ parentId: ParentData.id });
      this.getCouponPro(ParentData.id);
    }
    this.getProduct();
    this.fetchCategory();
  }
  getData = (id: number) => {
    const { dispatch } = this.props;
    if (id) {
      dispatch({
        type: 'Abp/get',
        payload: { id },
        control: currControl,
      }).then(() => {
        var result = this.props.response.result;

        if (result.startTime) result.startTime = moment(result.startTime);
        if (result.endTime) result.endTime = moment(result.endTime);
        if (result.type == '打折优惠券') {
          this.setState({ showDiscount: true });
        } else if (result.type == '抵扣优惠券') {
          this.setState({ showDeduction: true });
        } else if (result.type == '满减优惠券') {
          this.setState({ showFullminus: true });
        } else if (result.type == '学习券') {
          this.setState({ showStudy: true });
        }
        if (result.getMethod) {
          result.getMethod = result.getMethod.toString();
        }
        // if (result.isSuperposeOther) {
        result.isSuperposeOther = result.isSuperposeOther.toString();
        // }
        // if (result.isFreeGive) {
        result.isFreeGive = result.isFreeGive.toString();
        // }
        result.course = result.course?.split(',');
        this.formRef.current.setFieldsValue({ model: result });
      });
    }
  };
  getCouponPro = (id: number) => {
    this.props
      .dispatch({
        type: 'Abp/getByCouponId',
        payload: {
          couponid: id,
        },
      })
      .then(() => {
        let resp = this.props.response.result;
        let targetKeys: any = [];
        resp.forEach((item: any) => {
          targetKeys.push(item.id);
        });
        this.setState({ targetKeys, loadingP: false });
      });
  };
  getProduct = () => {
    let { params, categoryId } = this.state;
    if (categoryId == null) {
      categoryId = 0;
    }
    this.props
      .dispatch({
        type: 'Abp/getList',
        payload: {
          SkipCount: 0,
          MaxResultCount: 99999,
          categoryId,
          // isShelf: 1,
          ...params,
        },
        control: 'Edu_Product',
      })
      .then(() => {
        var resp = this.props.response;
        if (resp && resp.result) {
          var productData: any = [];
          resp.result.items?.forEach((element: any) => {
            productData.push({
              key: element.id,
              title: element.title,
              description: element.memo,
            });
          });
          this.setState({ productData, loadingP: false });
        }
      });
  };
  //产品分类数据
  fetchCategory = () => {
    this.props
      .dispatch({
        type: 'Category/getTreeData',
        payload: { layout: 'product' },
      })
      .then(() => {
        this.setState({ cascaderOption: this.props.Category.response.result });
      });
  };
  //添加优惠券适用产品
  handleAddPro = () => {
    let { parentId, targetKeys } = this.state;
    const ids = targetKeys?.join(',');
    if (parentId) {
      this.props
        .dispatch({
          type: 'Abp/updateCoupon',
          payload: {
            ids,
            couId: parentId,
          },
        })
        .then(() => {
          var resp = this.props.response;
          if (resp.success) {
            console.log('成功');
          }
          this.getCouponPro(parentId);
        });
    }
  };
  onFinish = async (values: any) => {
    let { targetKeys } = this.state;
    // return;
    var act = 'Abp/create';
    if (values.model.id) {
      act = 'Abp/update';
    }
    values.model.startTime = values.model.startTime?.format('YYYY-MM-DD');
    values.model.endTime = values.model.endTime?.format('YYYY-MM-DD');
    values.model.course = targetKeys.join(',');
    this.props
      .dispatch({
        type: act,
        payload: values.model,
        control: currControl,
      })
      .then(() => {
        var resp = this.props.response;
        if (resp.success) {
          this.handleAddPro();
          message.success('保存成功！');
          this.props.fetchDatas();
        } else {
          message.error('保存错误，请联系管理员');
        }
      });
  };
  handleTransChange = (nextTargetKeys: any, direction: any, moveKeys: any) => {
    this.setState({ targetKeys: nextTargetKeys });
  };

  handleSelectChange = (sourceSelectedKeys: any, targetSelectedKeys: any) => {
    this.setState({
      selectedKeys: [...sourceSelectedKeys, ...targetSelectedKeys],
    });
  };
  ResetForm = () => {
    var data = {
      id: 0,
    };
    this.setState({ datas: data });
    this.formRef.current.resetFields();
  };
  handleDel = () => {
    this.props
      .dispatch({
        type: 'Abp/delete',
        payload: { Id: this.state.datas.id },
        control: currControl,
      })
      .then(() => {
        var resp = this.props.response;
        if (resp.success) {
          message.success('删除成功！');
          this.props.fetchDatas();
          this.formRef.current.resetFields();
        } else {
          message.error('删除错误，请联系管理员！');
        }
      });
  };
  showConfirm = () => {
    var _this = this;
    confirm({
      title: '警告',
      icon: <ExclamationCircleOutlined />,
      content: '删除后将不可恢复，确定删除？',
      onOk() {
        _this.handleDel();
      },
      onCancel() {},
    });
  };
  handleChange = (editorState: any) => {
    this.setState({
      contentEditor: editorState.toHTML(),
    });
  };
  onChange = (value: number[]) => {
    this.setState({
      inputValue: value,
    });
  };
  handleUpload = (info: any) => {
    if (info.file.status === 'uploading') {
      this.setState({ loading: true });
      return;
    }
    if (info.file.status === 'done') {
      UploadUtil.getBase64(info.file.originFileObj, (imageUrl: any) =>
        this.setState({
          imageUrl,
          imgList: info.fileList,
          loading: false,
        }),
      );
    }
  };
  onCateSelChange = (value: any) => {
    this.setState({ categoryId: value });
  };
  handleSearch = () => {
    this.getProduct();
    this.setState({ loadingP: true });
  };
  handleRadio = (val: any) => {
    if (val.target.value == '打折优惠券') {
      this.setState({
        showDiscount: true,
        showDeduction: false,
        showFullminus: false,
        showStudy: false,
      });
    } else if (val.target.value == '抵扣优惠券') {
      this.setState({
        showDiscount: false,
        showDeduction: true,
        showFullminus: false,
        showStudy: false,
      });
    } else if (val.target.value == '满减优惠券') {
      this.setState({
        showDiscount: false,
        showDeduction: false,
        showFullminus: true,
        showStudy: false,
      });
    } else {
      this.setState({
        showDiscount: false,
        showDeduction: false,
        showFullminus: false,
        showStudy: true,
      });
    }
  };
  render() {
    const {
      loading,
      productData,
      targetKeys,
      selectedKeys,
      cascaderOption,
      categoryId,
      showDiscount,
      showDeduction,
      showFullminus,
      showStudy,
      parentId,
      loadingP,
    } = this.state;
    
    return (
      <div>
        <Form ref={this.formRef} layout="vertical" onFinish={this.onFinish}>
          <Tabs defaultActiveKey="1">
            <TabPane tab="基本" key="1">
              <div style={{ display: 'none' }}>
                <Form.Item label="id" name={['model', 'id']}>
                  <Input />
                </Form.Item>
              </div>
              <Col span={16}>
                <Form.Item
                  name={['model', 'title']}
                  label="优惠券名称"
                  rules={[{ required: true }]}
                >
                  <Input />
                </Form.Item>
              </Col>
              <Col span={16}>
                <Form.Item>
                  <Input.Group compact>
                    <Form.Item name={['model', 'startTime']} label="开始日期">
                      <DatePicker style={{ width: 180 }} />
                    </Form.Item>
                    <Form.Item name={['model', 'endTime']} label="截至日期">
                      <DatePicker style={{ width: 185 }} />
                    </Form.Item>
                  </Input.Group>
                </Form.Item>
              </Col>
              <Col span={16}>
                <Form.Item
                  name={['model', 'validDays']}
                  label="有效使用天数"
                  rules={[{ required: true }]}
                >
                  <InputNumber placeholder="请输入有效使用天数" min={0} style={{ width: '100%' }} />
                </Form.Item>
              </Col>
              <Col span={16}>
                <Form.Item name={['model', 'type']} label="优惠券类型" rules={[{ required: true }]}>
                  <Radio.Group onChange={this.handleRadio}>
                    <Radio value="打折优惠券">打折优惠券</Radio>
                    <Radio value="学习券">学习券</Radio>
                    <Radio value="抵扣优惠券">抵扣优惠券</Radio>
                    <Radio value="满减优惠券">满减优惠券</Radio>
                  </Radio.Group>
                </Form.Item>
              </Col>
              <Col span={16}>
                {showDiscount == true ? (
                  <Form.Item
                    name={['model', 'points']}
                    label="打折率"
                    rules={[{ required: true }]}
                    tooltip="打折率输入格式：0.88（意为8.8折），"
                  >
                    <InputNumber min={0} step="0.01" style={{ width: '100%' }} />
                  </Form.Item>
                ) : showDeduction == true ? (
                  <Form.Item
                    name={['model', 'points']}
                    label="抵扣金额"
                    rules={[{ required: true }]}
                    tooltip="抵扣价输入格式：88.00 （意为抵扣88豆币）"
                  >
                    <InputNumber min={0} step="0.01" style={{ width: '100%' }} />
                  </Form.Item>
                ) : showFullminus == true ? (
                  <Form.Item label="满减优惠券" rules={[{ required: true }]} tooltip="满多少减多少">
                    <Input.Group compact>
                      <Input placeholder="满" readOnly style={{ width: 60, textAlign: 'center' }} />
                      <Form.Item name={['model', 'maxDiscountAmt']} rules={[{ required: true }]}>
                        <Input style={{ width: 125, textAlign: 'center' }} placeholder="满减条件" />
                      </Form.Item>
                      <Input
                        className="site-input-split"
                        style={{
                          width: 60,
                          borderLeft: 0,
                          borderRight: 0,
                          pointerEvents: 'none',
                          textAlign: 'center',
                        }}
                        placeholder="减"
                        disabled
                      />
                      <Form.Item name={['model', 'discountAmt']} rules={[{ required: true }]}>
                        <Input
                          className="site-input-right"
                          style={{
                            width: 120,
                            textAlign: 'center',
                          }}
                          placeholder="优惠豆币"
                        />
                      </Form.Item>
                    </Input.Group>
                  </Form.Item>
                ) : showStudy == true ? (
                  <Form.Item
                    name={['model', 'points']}
                    label="学习券"
                    rules={[{ required: true }]}
                    tooltip="直接观看课程"
                  >
                    <InputNumber min={0} step="0.01" style={{ width: '100%' }} />
                  </Form.Item>
                ) : (
                  ''
                )}
              </Col>
              <Row gutter={4}>
                <Col span={6}>
                  <Form.Item
                    name={['model', 'couponQty']}
                    label="优惠券总量"
                    rules={[{ required: true }]}
                  >
                    <InputNumber placeholder="请输入优惠券总量" min={0} style={{ width: '100%' }} />
                  </Form.Item>
                </Col>
                <Col span={6}>
                  <Form.Item
                    name={['model', 'totalCount']}
                    label="发行量"
                    tooltip="发行量：用户已领取数量"
                  >
                    <InputNumber readOnly min={0} style={{ width: '100%' }} />
                  </Form.Item>
                </Col>
              </Row>
              <Col span={16}>
                <Form.Item
                  name={['model', 'getMethod']}
                  label="领取规则"
                  rules={[{ required: true }]}
                >
                  <Radio.Group>
                    <Radio value="0">不限</Radio>
                    <Radio value="1">每人限领一张</Radio>
                    <Radio value="2">每日可领一张</Radio>
                  </Radio.Group>
                </Form.Item>
              </Col>
              <Col span={16}>
                <Form.Item
                  name={['model', 'isSuperposeOther']}
                  label="是否与其他优惠券一起使用"
                  // rules={[{ required: true }]}
                >
                  <Radio.Group>
                    <Radio value="true">允许</Radio>
                    <Radio value="false">不允许</Radio>
                  </Radio.Group>
                </Form.Item>
              </Col>
              <Col span={16}>
                <Form.Item
                  name={['model', 'isFreeGive']}
                  label="是否允许免费赠送"
                  rules={[{ required: true }]}
                >
                  <Radio.Group>
                    <Radio value="true">允许</Radio>
                    <Radio value="false">不允许</Radio>
                  </Radio.Group>
                </Form.Item>
              </Col>
              {/* <Col span={12}>
                <Form.Item
                  name={['model', 'isApprve']}
                  label="是否审核"
                  // rules={[{ required: true }]}
                >
                  <Radio.Group>
                    <Radio value="true">已审核</Radio>
                    <Radio value="false">未审核</Radio>
                  </Radio.Group>
                </Form.Item>
              </Col> */}
              <Col span={22}>
                <Form.Item name={['model', 'memo']} label="优惠券说明" rules={[{ required: true }]}>
                  <Input.TextArea />
                </Form.Item>
              </Col>
            </TabPane>
            <TabPane tab="适用产品" key="2">
              <Row style={{ marginBottom: 14 }}>
                <Col span={10}>
                  <TreeSelect
                    allowClear
                    style={{ width: 210 }}
                    value={categoryId}
                    dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                    treeData={cascaderOption}
                    placeholder="请选择分类"
                    treeDefaultExpandAll
                    onChange={this.onCateSelChange}
                  />
                  <Button type="primary" icon={<SearchOutlined />} onClick={this.handleSearch}>
                    查询
                  </Button>
                </Col>
              </Row>
              <Form.Item name={['model', 'production']}>
                <Spin spinning={loadingP}>
                  <Transfer
                    dataSource={productData}
                    titles={['所有产品', '已选产品']}
                    targetKeys={targetKeys}
                    selectedKeys={selectedKeys}
                    onChange={this.handleTransChange}
                    onSelectChange={this.handleSelectChange}
                    render={(item: any) => item.title}
                    style={{ marginBottom: 16, width: '700px' }}
                    pagination
                  />
                </Spin>
              </Form.Item>
            </TabPane>
            
            <TabPane tab="兑换码" key="3">
            <CodeList couId={this.props.ParentData?.id}/>
            </TabPane>
          </Tabs>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit" loading={loading}>
                确定
              </Button>
              <Button onClick={this.ResetForm}>重设</Button>
              <Button danger onClick={this.showConfirm} disabled={!parentId}>
                删除
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </div>
    );
  }
}
export default connect(({ Abp, Category }: API.IConnectState) => ({
  response: Abp.response,
  currentUser: Abp.currentUser,
  Category,
}))(CourseEdit);
